#include <stdio.h>
#include  "ifsf.h"

int init_ifsf_udp()
{
	printf ("fucntion = %s\n" , __FUNCTION__ );
	
	return 0;
}

uint8 ifsf_is_msg(const char* buf, int len)
{
	char *tmp = (char* )buf;
	uint8 subnet;
	uint8 node;
	uint8 code;
	uint8 stat;
	uint8 type;
	uint16 mlen;

	/* LNAR */
	subnet = buf[0];
	node = buf[1];
	if (subnet < 1 || node < 1 || node > 127) {
		return IFSF_MSG_ERR_LNAR;
	}

	/* LNAO */
	subnet = buf[2];
	node = buf[3];
	if (subnet < 1 || node < 1 || node > 127) {
		return IFSF_MSG_ERR_LNAO;
	}

	/* Message Code */
	code = (uint8)buf[4] ;
	if (code < 1 || code > 2) {
		return IFSF_MSG_ERR_MC;
	}

	/* Message Status */
	stat = (uint8) buf[5];
	type = IFSF_MSGTYPE_MASK & stat;
	if (!((type == IFSF_MSGTYPE_READ) ||
					(type == IFSF_MSGTYPE_WRITE) || 
					(type == IFSF_MSGTYPE_ANSWER) ||
					(type == IFSF_MSGTYPE_UNSOL_ACK) || 
					(type == IFSF_MSGTYPE_UNSOL) ||
					(type == IFSF_MSGTYPE_ACK)) ) {
		return IFSF_MSG_ERR_ST;
	}

	/* Message Length */
	mlen = (uint16) ((buf[6] << 8) | (buf[7]));
	if (mlen + 8 < len) {
		return IFSF_MSG_ERR_LG;
	}

	return type;
}


int ifsf_heartbeat (uint16 lnao, uint8 ds)
{
	char buf[4];

	buf[0] = ifsf_subnet(lnao);
	buf[1] = ifsf_node (lnao);
	buf[2] = 1;
	buf[3] = ds;

	return iipc_heartbeat(buf, 4);
}

int ifsf_handle_readmsg(const char* buf, int len)
{
	uint16 lnar;
	uint16 lnao;
	uint16 mlg;
	uint8 token;
	uint8 db_len;
	uint64 db;
	uint8 *ids;
	uint8 id;

	db_len = buf[8];
	
	mlg = ifsf_mlg(buf[6], buf[7]);

	id_nums = mlg - db_len - 1;

	for (i=0; i<id_nums; i++) {
		len = ifsf_db_get_data(db, db_len, id);
	}

	
	ifsf_send_answer_msg(const char* buf, int len);
	return 0;

read_err:
	ifsf_send_ack_msg();
	return -1;
}

int ifsf_handle_write_msg(const char* buf, int len)
{
    for (i=0; i<id_nums; i++) {
        id = ids[i].id;
        id_len = ids[i].len;
        ack = ifsf_db_set_data(db, db_len, id, id_len, value);
    }

    ifsf_send_ack_msg(ack_buf, ack_len);
    return 0;
}

int ifsf_handle_unsol_msg(const char* buf, int len)
{
    return 0;
}

int ifsf_send_answer_msg(const char* buf, int len)
{
    return 0;
}

int ifsf_send_ack_msg(const char* buf, int len)
{
    return 0;
}

int ifsf_send_unsol_msg(const char* buf, int len)
{
    return 0;
}

int ifsf_send_read_msg(const char* buf, int len)
{
    return 0;
}

int ifsf_send_write_msg(const char* buf, int len)
{
    return 0;
}

int ifsf_send_unsol_ack_msg(const char* buf, int len)
{
    return 0;
}


